package com.yicong.taxi.activity;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;

import com.hjq.toast.ToastUtils;
import com.qiniu.android.http.ResponseInfo;
import com.qiniu.android.storage.UpCompletionHandler;
import com.qiniu.android.storage.UploadManager;
import com.qiniu.util.Auth;
import com.yicong.taxi.R;
import com.yicong.taxi.base.BaseActivity;
import com.yicong.taxi.iview.RegisterView;
import com.yicong.taxi.presenter.RegisterPresenter;

import org.json.JSONObject;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class RegisterActivity extends BaseActivity<RegisterPresenter> implements RegisterView {

    @BindView(R.id.img_id_front) ImageView imgIdFront;
    @BindView(R.id.img_id_back) ImageView imgIdBack;
    @BindView(R.id.img_driving_front) ImageView imgDrivingFront;
    @BindView(R.id.img_driving_back) ImageView imgDrivingBack;
    @BindView(R.id.img_obtain) ImageView imgObtain;
    @BindView(R.id.img_work_license) ImageView imgWorkLicense;
    @BindView(R.id.et_name) EditText etName;
    @BindView(R.id.et_phone) EditText etPhone;
    @BindView(R.id.et_code) EditText etCode;
    @BindView(R.id.btn_commit) Button btnCommit;
    private int IMG_ID_FRONT = 0;//身份证正面
    private int IMG_ID_BACK = 1; //身份证反面
    private int IMG_DRIVING_FRONT = 2; //驾驶证正页
    private int IMG_DRIVING_BACK = 3; //驾驶证副页
    private int IMG_OBTAIN = 4; //从业资格证
    private int IMG_LICENSE = 5; //上岗证
    private String[] mImgNames = {"id_front", "id_back", "driving_front", "driving_back", "obtain", "license"};
    private ImageView[] mImageViews;
    private String[] mFilePath = new String[6];
    private String[] mImgUrls;
    private int mUploadId;

    public static final int TAKE_PHOTO = 1;
    public static final String IMAGE_URL = "com.yicong.taxi.image";//用Intent传递给UploadActivity时的key
    public static final String IMAGE_NAME = "cyy";//getExternalCacheDir()取得的图片名称
    public static final String DEFAULT_URL = "http://puzbvwnp5.bkt.clouddn.com";//七牛云指定的域名

    private Uri photoUri;
    private String filePath;  //图片路径

    //    private Uri imageUri;//图片Uri
    private static Handler mHander = new Handler();//在子线程中用于和主线程交互

    private boolean hasPicture = false;

    //在客户端中生成上传需要的token
    private String accessKey = "4_aYuuFk0q5GAyaqtBNzSV-UvNG2knaHD88zr2cf";
    private String secretKey = "CTZN8ZtxIIZCw-4NjGaTvUupUgqWYqx3lpOuGtxW";
    //七牛云创建的储存位置名字
    private String bucket = "tax";

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_register;
    }

    @Override
    protected void initPresenter() {
        presenter = new RegisterPresenter(mActivity, this, this);
        presenter.init();
    }

    @Override
    public void initView() {
        mImageViews = new ImageView[]{imgIdFront, imgIdBack, imgDrivingFront, imgDrivingBack, imgObtain, imgWorkLicense};
        mImgUrls=new String[]{"","","","","",""};
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            try {
                Bitmap bitmap = compressBySize(mFilePath[requestCode], 1000, 600);  //设置压缩后图片的高度和宽度
                saveFile(bitmap, mFilePath[requestCode]);
                mImageViews[requestCode].setImageBitmap(bitmap);
                hasPicture = true;
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

    @OnClick({R.id.img_id_front, R.id.img_id_back,
            R.id.img_driving_front, R.id.img_driving_back,
            R.id.img_obtain, R.id.img_work_license, R.id.btn_commit})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.img_id_front:
                startPhoto(IMG_ID_FRONT);
                break;
            case R.id.img_id_back:
                startPhoto(IMG_ID_BACK);
                break;
            case R.id.img_driving_front:
                startPhoto(IMG_DRIVING_FRONT);
                break;
            case R.id.img_driving_back:
                startPhoto(IMG_DRIVING_BACK);
                break;
            case R.id.img_obtain:
                startPhoto(IMG_OBTAIN);
                break;
            case R.id.img_work_license:
                startPhoto(IMG_LICENSE);
                break;
            case R.id.btn_commit:
                String name = etName.getText().toString().trim();
                String phone = etPhone.getText().toString().trim();
                String code = etCode.getText().toString().trim();
                if (TextUtils.isEmpty(name)) {
                    ToastUtils.show("请输入姓名");
                } else if (TextUtils.isEmpty(phone)) {
                    ToastUtils.show("请输入电话号码");
                } else if (!hasPicture) {
                    ToastUtils.show("请拍照设置图片");
                } else {
                    mUploadId = 0;
                    final ProgressDialog progressDialog = new ProgressDialog(RegisterActivity.this);
                    progressDialog.setTitle("正在上传图片");
                    progressDialog.setMessage("上传中....");
                    progressDialog.setCancelable(false);
                    progressDialog.show();
                    //生成token
                    Auth auth = Auth.create(accessKey, secretKey);
                    String upToken = auth.uploadToken(bucket);
                    //开启子线程上传图片
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            //系统现在秒数作为上传用的图片名称
                            uploadImg(mUploadId);
                        }

                        private void uploadImg(int imgId) {
                            String key = phone+"_"+mImgNames[imgId];
                            UploadManager uploadManager = new UploadManager();
                            File file = new File(mFilePath[mUploadId]);
                            //上传图片
                            uploadManager.put(file, key, upToken, new UpCompletionHandler() {
                                @Override public void complete(String key1, ResponseInfo info, JSONObject response) {
                                    //成功则跳转至UploadActivity，并根据图片Url地址显示出图片
                                    if (info.isOK()) {
                                        mImgUrls[mUploadId] = DEFAULT_URL + "/" + key1;
                                        mUploadId++;
                                        if (mUploadId <= 5 && !TextUtils.isEmpty(mFilePath[mUploadId])) {
                                            uploadImg(mUploadId);
                                        } else {
                                            progressDialog.dismiss();
                                            ToastUtils.show("图片上传完毕！");

                                            presenter.register(name, phone, mImgUrls[0], mImgUrls[1], mImgUrls[2],
                                                    mImgUrls[3], mImgUrls[4], mImgUrls[5]);
                                        }
                                    } else {
                                        //失败则提示
                                        progressDialog.dismiss();
                                        mHander.post(() -> {
                                            if (hasPicture) {
                                                ToastUtils.show("未连接网络");
                                            } else {
                                                ToastUtils.show("没有图片可以上传");
                                            }
                                        });

                                    }
                                }
                            }, null);
                        }
                    }) {
                    }.start();

                }

                break;
        }
    }

    private void startPhoto(int imgId) {
        Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
        intent.putExtra(MediaStore.EXTRA_OUTPUT, getImgUri(imgId));
        startActivityForResult(intent, imgId);
    }

    /**
     * 图片保存路径  这里是在SD卡目录下创建了YiCong文件夹
     *
     * @return
     */
    private Uri getImgUri(int imgId) {  //指定了图片的名字，可以使用时间来命名
        // TODO Auto-generated method stub
        String strPhotoName =mImgNames[imgId] + ".jpg";
        String savePath = Environment.getExternalStorageDirectory() + "/YiCong/";
        File dir = new File(savePath);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        filePath = savePath + strPhotoName;
        mFilePath[imgId] = filePath;

        if (Build.VERSION.SDK_INT >= 24) {
            photoUri = FileProvider.getUriForFile(
                    this,
                    "com.yicong.taxi.fileprovider",
                    new File(dir, strPhotoName));
        } else {
            photoUri = Uri.fromFile(new File(dir, strPhotoName));
        }
        return photoUri;
    }

    // 压缩图片尺寸
    private Bitmap compressBySize(String pathName, int targetWidth,
                                  int targetHeight) {
        BitmapFactory.Options opts = new BitmapFactory.Options();
        opts.inJustDecodeBounds = true;// 不去真的解析图片，只是获取图片的头部信息，包含宽高等；
        Bitmap bitmap = BitmapFactory.decodeFile(pathName, opts);
        // 得到图片的宽度、高度；
        float imgWidth = opts.outWidth;
        float imgHeight = opts.outHeight;
        // 分别计算图片宽度、高度与目标宽度、高度的比例；取大于等于该比例的最小整数；
        int widthRatio = (int) Math.ceil(imgWidth / (float) targetWidth);
        int heightRatio = (int) Math.ceil(imgHeight / (float) targetHeight);
        opts.inSampleSize = 1;
        if (widthRatio > 1 || widthRatio > 1) {
            if (widthRatio > heightRatio) {
                opts.inSampleSize = widthRatio;
            } else {
                opts.inSampleSize = heightRatio;
            }
        }
        // 设置好缩放比例后，加载图片进内容；
        opts.inJustDecodeBounds = false;
        bitmap = BitmapFactory.decodeFile(pathName, opts);
        return bitmap;
    }

    //保存压缩后的图片
    private void saveFile(Bitmap bitmap, String filePath2) throws IOException {
        // TODO Auto-generated method stub
        File testFile = new File(filePath2);
        if (testFile.exists()) {
            testFile.delete();
        }
        File myCaptureFile = new File(filePath2);
        BufferedOutputStream bos = new BufferedOutputStream(
                new FileOutputStream(myCaptureFile));
        // 100表示不进行压缩，70表示压缩率为30%
        bitmap.compress(Bitmap.CompressFormat.JPEG, 60, bos);
        bos.flush();
        bos.close();
    }

    /**
     * 判断是否通过权限
     *
     * @param grantResults
     * @return
     */
    private boolean checkPermission(int[] grantResults) {
        return grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED;
    }

    /**
     * 判断是否没有permissionType的权限
     *
     * @param context
     * @param permissionType
     * @return
     */
    private boolean hasNoPermission(Context context, String permissionType) {
        return ContextCompat.checkSelfPermission(context, permissionType) != PackageManager.PERMISSION_GRANTED;
    }

    /**
     * *请求获取permissionType的权限
     *
     * @param activity
     * @param permissionType
     * @param code
     */
    private void requestPermission(Activity activity, String permissionType, int code) {
        ActivityCompat.requestPermissions(activity, new String[]{permissionType}, code);
    }


    @Override public void registerSuccess() {
        ToastUtils.show("提交成功！");
    }
}
